package com.dayuanit.pay.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.dayuanit.pay.dao.PayOrderDao;
import com.dayuanit.pay.domain.PayOrder;
import com.dayuanit.pay.domain.PayType;
import com.dayuanit.pay.mallenum.PayStatus;
import com.dayuanit.pay.mallenum.PayTypeEnum;
import com.dayuanit.pay.service.PayService;

@Service
@WebService(endpointInterface = "com.dayuanit.pay.service.PayService")
public class PayServiceImpl implements PayService {
	
	@Value("#{configProperties['dayuanit.pay.topay.url']}")
	private String payUrl;
	
	@Autowired
	private PayOrderDao payOrderDao;
	
	@Override
	public Map<String, Object> addPayOrder(PayOrder payOrder) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("payOrderUrl", payUrl + "?payId=" + payOrder.getId());
		map.put("payId", payOrder.getId());
		map.put("success", true);
		map.put("message", "");
		
		PayOrder loadPayOrder = payOrderDao.getPayOrderByBizId(payOrder.getBizId(), payOrder.getUserId());
		if (null != loadPayOrder) {
			orderExistProcess(loadPayOrder, map);
		} else {
			orderUnExistProcess(payOrder, map);
		}
		
		return map;
	}
	
	private void orderExistProcess(PayOrder payOrder, Map<String, Object> map) {
		if (payOrder.getStatus() == PayStatus.UNPAID.getStatus() || payOrder.getStatus() == PayStatus.PAY_FAILURE.getStatus()) {
			map.put("payId", payOrder.getId());
			map.put("payOrderUrl", payUrl + "?payId=" + payOrder.getId());
		} else {
			map.put("success", false);
			map.put("message", "订单" + PayStatus.getPayStatus(payOrder.getStatus()).getMsg());
		}
	}
	
	private void orderUnExistProcess(PayOrder payOrder, Map<String, Object> map) {
		int rows = payOrderDao.addPayOrder(payOrder);
		if (rows != 1) {
			map.put("success", false);
			map.put("message", "支付订单处理失败");
		}
		
		map.put("payId", payOrder.getId());
		map.put("payOrderUrl", payUrl + "?payId=" + payOrder.getId());
	}


	@Override
	public List<PayType> listPayType() {
		
		List<PayType> payList = new ArrayList<PayType>();
		
		for (PayTypeEnum pe : PayTypeEnum.values()) {
			PayType pt = new PayType();
			pt.setPayCode(pe.getType());
			pt.setPayDesc(pe.getDesc());
			payList.add(pt);
		}
		
		return payList;
	}


	@Override
	public String getPayName(int payType) {
		return PayTypeEnum.getPayType(payType).getDesc();
	}

	@Override
	public PayOrder getPayOrder(int payId) {
		return payOrderDao.getPayOrderById(payId);
	}
	
	

}
